package com.xy6.jvm.atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * AtomicInteger实现计数示例
 * 
 * @author zhang
 *
 */
public class AtomicCounter {

	private AtomicInteger value = new AtomicInteger();

	public int getValue() {
		return value.get();
	}

	public int increase() {
		return value.incrementAndGet();
	}

	public int increase(int i) {
		return value.addAndGet(i);
	}

	public int decrease() {
		return value.decrementAndGet();
	}

	public int decrease(int i) {
		return value.addAndGet(-i);
	}

	public static void main(String[] args) {
		final AtomicCounter counter = new AtomicCounter();
		ExecutorService service = Executors.newCachedThreadPool();
		for(int i=0; i<10; i++){
			service.execute(new Runnable(){
				@Override
				public void run(){
					System.out.println(counter.increase());
				}
			});
		}
		service.shutdown();
		System.out.println(counter.value);
	}
}
